import type { FC } from "react";
import { useAsyncEffect } from "ahooks";
import useUserState from "@/models/user";
import Loading from "@/components/Loading";
import { Navigate, useLocation, useSearchParams } from "react-router-dom";

const LOGIN_PATH = "/user/login";
const USER_PATHS = [LOGIN_PATH];

interface IOptions {
  skipTokenFn?: (urlParams: URLSearchParams) => boolean;
}

const AuthorizationWrapper = (Component: FC<any>, opts?: IOptions) => () => {
  const user = useUserState();
  const { pathname } = useLocation();
  const [urlQuery] = useSearchParams();

  useAsyncEffect(user.initialization, []);

  if (!user.initialized) return <Loading />;

  // 检查是否需要跳过登录
  if (!opts?.skipTokenFn?.(urlQuery)) {
    const isUserUrl = USER_PATHS.includes(pathname);

    // 检查登录逻辑
    if (user.token) {
      if (isUserUrl) {
        return <Navigate to="/" replace />;
      }
    } else {
      if (!isUserUrl) {
        return <Navigate to={LOGIN_PATH} replace />;
      }
    }
  }

  return (
    <Component
      token={user.token}
      urlQuery={urlQuery}
    />
  );
}

export default AuthorizationWrapper;
